# Create your views here.
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response

from goods.models import GoodsCategory, SKU
from goods.serializers import GoodsCategorySerialize, GoodsChannelSerialize, SKUSerializer, SKUIndexSerializer
from meiduo_mall.utils.pagination import StandardResultsSetPagination


class GoodsBreadcrumbAPIView(GenericAPIView):

	queryset = GoodsCategory.objects.all()

	def get(self, request, pk):
		try:
			category = self.get_object()
		except:
			return Response({"message": "category参数错误"}, status=402)

		data = {}

		if not category.parent:
			data['cat1'] = GoodsChannelSerialize(category.goodschannel_set.all()[0]).data
		elif category.goodscategory_set.count()==0:
			data['cat3'] = GoodsCategorySerialize(category).data
			category_parent = category.parent
			data['cat2'] = GoodsCategorySerialize(category_parent).data
			data['cat1'] = GoodsChannelSerialize(category_parent.parent.goodschannel_set.all()[0]).data
		else:
			data['cat2'] = GoodsCategorySerialize(category).data
			data['cat1'] = GoodsChannelSerialize(category.parent.goodschannel).data

		return Response(data, status=200)


class SKUListView(ListAPIView):
	"""
	返回SKU详情
	"""
	serializer_class = SKUSerializer
	filter_backends = [OrderingFilter]
	ordering_filder = ['create_time','price','sales']
	pagination_class = StandardResultsSetPagination

	def get_queryset(self):
		pk = self.kwargs.get('pk')
		return SKU.objects.filter(category_id=pk, is_launched=True)


class SKUSearchViewSet(HaystackViewSet):
	"""
	SKU搜索
	"""
	index_models = [SKU]
	serializer_class = SKUIndexSerializer
